package org.example.controller;


import jakarta.validation.constraints.Pattern;
import org.example.pojo.Result;
import org.example.pojo.User;
import org.example.service.UserService;
import org.example.utils.JwtUtil;
import org.example.utils.Md5Util;
import org.example.utils.ThreadLocalUtil;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController //包含了RequestBody
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 用户注册
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/register")
    public Result Register(@Pattern(regexp="^\\S{5,16}$") String username,@Pattern(regexp="^\\S{5,16}$") String password){

        //查询用户
        User u = userService.findByUserName(username);
        if(u==null){
            //用户名没有被占用
            //这里完成注册
            userService.register(username,password);
            return Result.success();
        }else{
            //用户名被占用了
            return Result.error("该用户名已被占用");
        }


    }


    /**
     * 用户登录
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username,@Pattern(regexp = "^\\S{5,16}$") String password){
        //查看数据库中是否有该用户
        User LoginUser = userService.findByUserName(username);
        //如果没有这个用户我们直接报错就好啦!
        if(LoginUser == null){
            return Result.error("用户名错误");
        }
        //证明有这个用户 接着来检验密码
        if(Md5Util.getMD5String(password).equals(LoginUser.getPassword())){
            Map<String,Object>claims = new HashMap<>();
            claims.put("id",LoginUser.getId());
            claims.put("username",LoginUser.getUsername());
            String token = JwtUtil.genToken(claims);
            //把token存储到Redis中
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token,token,1, TimeUnit.HOURS);//跟token过期时间一致
            /*
            用redis优化登录，把token作为key又作为value存入redis有一个bug，
            当在两个不同浏览器同时登录同一个账号，它们登陆时使用的是不同的token，
            一方修改密码不会影响另外一方的操作。
            因为没有做单点登录，所以这个问题肯定是存在的
            可以把key该为id
             */
            return Result.success(token);
        }
        return Result.error("密码错误");
    }

    /**
     * 获取用户详细信息
     * @return
     */
    @GetMapping("/userInfo")
    public Result<User>userInfo(/*@RequestHeader(name="Authorization")String token*/) {//token从请求头中获取的
        //根据用户名查询用户
//        Map<String, Object> map = JwtUtil.parseToken(token);
//        String username = (String)map.get("username");
        Map<String,Object>map = ThreadLocalUtil.get();
        String username = (String)map.get("username");
        User user = userService.findByUserName(username);
        //不能把password响应回去
        return Result.success(user);
    }

    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user){
        //加了validated才能生效
        userService.update(user);
        return Result.success();
    }

    /**
     * 更新用户头像
     * @param avatarUrl
     * @return
     */
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl){//表明从请求中获取这个请求参数
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String,String>params,@RequestHeader("Authorization") String token){
        //1.校验参数
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");

        if(!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)){
            return Result.error("缺少必要的参数");
        }
        //校验原密码是否正确
        //调用userService根据用户名拿到原密码,再和old_pwd比对
        Map<String,Object> map  = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User Loginuser = userService.findByUserName(username);
        if(!Loginuser.getPassword().equals(Md5Util.getMD5String(oldPwd))){
            return Result.error("原密码填写不正确~");
        }

        //newPwd和rePwd是否一样
        if(!rePwd.equals(newPwd)){
            return Result.error("两次填写的新密码不一致~");
        }
        //2.调用service完成密码更新
        userService.updatePwd(newPwd);
        //删除redis中对应的token
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(token);
        return Result.success();
    }

}
